Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
In [47]:
from sklearn.datasets import load_files       
from keras.utils import np_utils
import numpy as np
from glob import glob
import pandas as pd

# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('/data/dog_images/train')
valid_files, valid_targets = load_dataset('/data/dog_images/valid')
test_files, test_targets = load_dataset('/data/dog_images/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("/data/dog_images/train/*/"))]

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.
In [48]:
# Just had to see what this looked like

#train_files
#train_targets
#valid_files
#valid_targets
#test_files
#test_targets
#dog_names

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

In [49]:
import random
random.seed(8675309)

# load filenames in shuffled human dataset
human_files = np.array(glob("/data/lfw/*/*"))
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
There are 13233 total human images.

Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [50]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[np.random.randint(0,len(human_files))])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1
In [51]:
# put the code above into a function for use below.

def find_face(img_path):
    # load color (BGR) image
    img = cv2.imread(img_path)
    # convert BGR image to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # find faces in image
    faces = face_cascade.detectMultiScale(gray)

    # print number of faces detected in the image
    print('Number of faces detected:', len(faces))

    # get bounding box for each detected face
    for (x,y,w,h) in faces:
        # add bounding box to color image
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

    # convert BGR image to RGB for plotting
    cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    # display the image, along with bounding box
    plt.imshow(cv_rgb)
    plt.show()
    print (faces,"\n")

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [52]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer:

In [53]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.

human_files_short_results = []

for img in human_files_short:
    human_files_short_results.append(face_detector(img))

human_answer = np.round((np.sum(human_files_short_results) / len(human_files_short)) * 100, 2)
print('Percentage of first 100 images that detected human faces for HUMAN Dataset:',human_answer,'%')

dog_files_short_results = []

for img in dog_files_short:
    dog_files_short_results.append(face_detector(img))

dog_answer = np.round((np.sum(dog_files_short_results) / len(dog_files_short)) * 100, 2)
print('Percentage of first 100 images that detected human faces for for DOG Dataset:',dog_answer,'%')
Percentage of first 100 images that detected human faces for HUMAN Dataset: 100.0 %
Percentage of first 100 images that detected human faces for for DOG Dataset: 11.0 %
In [54]:
#get a list of the false positives to visualize

false_positives = []

index = 0
while index < len(dog_files_short_results):
    if dog_files_short_results[index]:
        false_positives.append(index)
        index+=1
    else:
        index+=1
In [55]:
#false positives for the DOG dataset

false_positives
Out[55]:
[0, 14, 15, 21, 22, 23, 24, 30, 32, 63, 78]
In [56]:
# display all the false positives from the DOG test files
from IPython.display import Image

for i in false_positives:
    #display(Image(dog_files_short[i], width=200, height=200))
    find_face(dog_files_short[i])
Number of faces detected: 1
[[160 159 108 108]] 

Number of faces detected: 1
[[189 140 100 100]] 

Number of faces detected: 1
[[202  95  48  48]] 

Number of faces detected: 1
[[237 175  81  81]] 

Number of faces detected: 1
[[107  38 247 247]] 

Number of faces detected: 1
[[237 135  48  48]] 

Number of faces detected: 1
[[366 137  34  34]] 

Number of faces detected: 1
[[1078 1034   44   44]] 

Number of faces detected: 1
[[390 322  49  49]] 

Number of faces detected: 1
[[162 272 213 213]] 

Number of faces detected: 1
[[302  57  98  98]] 

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer:

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.

In [57]:
## (Optional) TODO: Report the performance of another  
## face detection algorithm on the LFW dataset
### Feel free to use as many code cells as needed.

Answer:

In my opinion it is reasonable to expect that images meet some specifications espeically if you can make clear what the expectations are.


Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

In [58]:
from keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

In [59]:
from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

In [60]:
from keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [61]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

In [62]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.

human_files_short_results_2 = []

for img in human_files_short:
    human_files_short_results_2.append(dog_detector(img))

human_answer_2 = np.round((np.sum(human_files_short_results_2) / len(human_files_short)) * 100,1)
print('Percentage of first 100 images that detected DOGS for the HUMAN Dataset:',human_answer_2,'%')

dog_files_short_results_2 = []

for img in dog_files_short:
    dog_files_short_results_2.append(dog_detector(img))

dog_answer_2 = np.round((np.sum(dog_files_short_results_2) / len(dog_files_short)) * 100, 1)
print('Percentage of first 100 images that detected DOGS for the DOG Dataset:',dog_answer_2,'%')
Percentage of first 100 images that detected DOGS for the HUMAN Dataset: 0.0 %
Percentage of first 100 images that detected DOGS for the DOG Dataset: 100.0 %

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

In [63]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
100%|██████████| 6680/6680 [01:15<00:00, 87.96it/s] 
100%|██████████| 835/835 [00:11<00:00, 72.80it/s] 
100%|██████████| 836/836 [00:10<00:00, 81.42it/s] 

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.

Answer:

The architecture that you see below is what I have landed at after a bit of experimentation. I decided to use the architecture provided above as a starting point and see how much I could improve it.

This is had led me down the following approximate path:

  • Replicate the results above with the suggested architecture.
    • ~ 1% accuracy
  • Remove the GAP layer after the convolution layers and replace with another MaxPool layer.
    • ~ 10% accuracy
  • Experimenting with Dropout layers after the MaxPool and Fully Connected layers to help reduce overfit on the training data.
    • ~ 10% accuracy
  • Experimenting with the size and number of the fully connected layers
    • ~ 10% accuracy
  • Experimenting with the number of epochs to train the model
    • ~ 10% accuracy
  • Experiment with BatchNormalization after each conv layer
    • ~ 10% accuracy

Although it makes the code block below a big ugly. I've left in a bunch of commented out lines that shows some of the things I was trying here in getting to the architecture I've arrived at.

I'm still developing my intition as to why this works per se. But I believe it goes something like this:

  • The Conv2D layers build feature maps of what's contained in the images.
  • As the number of filters increases with each Conv2D layer, the detail in the each feature map increases.
    • Ie. We move from edge detection and detection of blobs/areas of color towards filters that begin to resemble the kinds of details that seem intuitive to a human eye.
  • I've used relu activation for all the layers until the softmax activation for the final fully connected layer in order to get a probabilty for each class.
  • I added a Flatten layer after the last max pooling layer in order to transition from the Max Pooling layers to the fully connected Dense layers.
  • I added a dropout layer towards the end as I saw that the model was starting to overfit on the training data with no subsequent decrease in validation loss.
In [64]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense, BatchNormalization
from keras.models import Sequential

model = Sequential()
model.add(Conv2D(input_shape=(224, 224, 3), filters=16, kernel_size=2, padding='same', activation='relu'))
#model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=32, kernel_size=2, padding='same', activation='relu'))
#model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=64, kernel_size=2, padding='same', activation='relu'))
#model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=128, kernel_size=2, padding='same', activation='relu'))
#model.add(Conv2D(filters=128, kernel_size=2, padding='same', activation='relu'))
#model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=256, kernel_size=2, padding='same', activation='relu'))
#model.add(Conv2D(filters=256, kernel_size=2, padding='same', activation='relu'))
#model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=2))
#model.add(Conv2D(filters=512, kernel_size=2, padding='same', activation='relu'))
#model.add(MaxPooling2D(pool_size=1))
#model.add(Dropout(0.2))
#model.add(Flatten())
#model.add(GlobalAveragePooling2D())
#model.add(Dropout(0.3))
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
#model.add(Dense(512, activation='relu'))
#model.add(Dropout(0.4))
model.add(Dense(133, activation='softmax'))

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_11 (Conv2D)           (None, 224, 224, 16)      208       
_________________________________________________________________
max_pooling2d_13 (MaxPooling (None, 112, 112, 16)      0         
_________________________________________________________________
conv2d_12 (Conv2D)           (None, 112, 112, 32)      2080      
_________________________________________________________________
max_pooling2d_14 (MaxPooling (None, 56, 56, 32)        0         
_________________________________________________________________
conv2d_13 (Conv2D)           (None, 56, 56, 64)        8256      
_________________________________________________________________
max_pooling2d_15 (MaxPooling (None, 28, 28, 64)        0         
_________________________________________________________________
conv2d_14 (Conv2D)           (None, 28, 28, 128)       32896     
_________________________________________________________________
max_pooling2d_16 (MaxPooling (None, 14, 14, 128)       0         
_________________________________________________________________
conv2d_15 (Conv2D)           (None, 14, 14, 256)       131328    
_________________________________________________________________
max_pooling2d_17 (MaxPooling (None, 7, 7, 256)         0         
_________________________________________________________________
flatten_5 (Flatten)          (None, 12544)             0         
_________________________________________________________________
dense_8 (Dense)              (None, 512)               6423040   
_________________________________________________________________
dropout_4 (Dropout)          (None, 512)               0         
_________________________________________________________________
dense_9 (Dense)              (None, 133)               68229     
=================================================================
Total params: 6,666,037
Trainable params: 6,666,037
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [65]:
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [66]:
from keras.callbacks import ModelCheckpoint

### TODO: specify the number of epochs that you would like to use to train the model.

epochs = 15

### Do NOT modify the code below this line.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=1, save_best_only=True)

hist = model.fit(train_tensors, train_targets, 
          validation_data=(valid_tensors, valid_targets),
          epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/15
6660/6680 [============================>.] - ETA: 0s - loss: 4.8749 - acc: 0.0113Epoch 00001: val_loss improved from inf to 4.69507, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 33s 5ms/step - loss: 4.8745 - acc: 0.0114 - val_loss: 4.6951 - val_acc: 0.0228
Epoch 2/15
6660/6680 [============================>.] - ETA: 0s - loss: 4.5374 - acc: 0.0393Epoch 00002: val_loss improved from 4.69507 to 4.41949, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 28s 4ms/step - loss: 4.5366 - acc: 0.0397 - val_loss: 4.4195 - val_acc: 0.0455
Epoch 3/15
6660/6680 [============================>.] - ETA: 0s - loss: 4.1884 - acc: 0.0703Epoch 00003: val_loss improved from 4.41949 to 4.17359, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 28s 4ms/step - loss: 4.1880 - acc: 0.0702 - val_loss: 4.1736 - val_acc: 0.0778
Epoch 4/15
6660/6680 [============================>.] - ETA: 0s - loss: 3.8749 - acc: 0.1099Epoch 00004: val_loss improved from 4.17359 to 4.02808, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 28s 4ms/step - loss: 3.8750 - acc: 0.1099 - val_loss: 4.0281 - val_acc: 0.0946
Epoch 5/15
6660/6680 [============================>.] - ETA: 0s - loss: 3.4653 - acc: 0.1845Epoch 00005: val_loss improved from 4.02808 to 3.93421, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 28s 4ms/step - loss: 3.4670 - acc: 0.1841 - val_loss: 3.9342 - val_acc: 0.1030
Epoch 6/15
6660/6680 [============================>.] - ETA: 0s - loss: 2.9045 - acc: 0.2785Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 28s 4ms/step - loss: 2.9042 - acc: 0.2786 - val_loss: 4.0604 - val_acc: 0.1018
Epoch 7/15
6660/6680 [============================>.] - ETA: 0s - loss: 2.2244 - acc: 0.4314Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 28s 4ms/step - loss: 2.2227 - acc: 0.4316 - val_loss: 4.6628 - val_acc: 0.1257
Epoch 8/15
6660/6680 [============================>.] - ETA: 0s - loss: 1.5219 - acc: 0.5968Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 28s 4ms/step - loss: 1.5219 - acc: 0.5970 - val_loss: 5.2616 - val_acc: 0.1150
Epoch 9/15
6660/6680 [============================>.] - ETA: 0s - loss: 0.9425 - acc: 0.7380Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 28s 4ms/step - loss: 0.9411 - acc: 0.7385 - val_loss: 6.7774 - val_acc: 0.1257
Epoch 10/15
6660/6680 [============================>.] - ETA: 0s - loss: 0.6102 - acc: 0.8240Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 28s 4ms/step - loss: 0.6105 - acc: 0.8238 - val_loss: 6.5930 - val_acc: 0.1174
Epoch 11/15
6660/6680 [============================>.] - ETA: 0s - loss: 0.4251 - acc: 0.8784Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 28s 4ms/step - loss: 0.4258 - acc: 0.8784 - val_loss: 7.9605 - val_acc: 0.1078
Epoch 12/15
6660/6680 [============================>.] - ETA: 0s - loss: 0.3426 - acc: 0.9035Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 28s 4ms/step - loss: 0.3431 - acc: 0.9033 - val_loss: 8.2295 - val_acc: 0.1281
Epoch 13/15
6660/6680 [============================>.] - ETA: 0s - loss: 0.2820 - acc: 0.9204Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 28s 4ms/step - loss: 0.2840 - acc: 0.9198 - val_loss: 8.6598 - val_acc: 0.1126
Epoch 14/15
6660/6680 [============================>.] - ETA: 0s - loss: 0.2514 - acc: 0.9275Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 28s 4ms/step - loss: 0.2509 - acc: 0.9275 - val_loss: 7.8796 - val_acc: 0.1090
Epoch 15/15
6660/6680 [============================>.] - ETA: 0s - loss: 0.2247 - acc: 0.9396Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 28s 4ms/step - loss: 0.2244 - acc: 0.9397 - val_loss: 9.0215 - val_acc: 0.1198
In [67]:
#ADAPTED FROM HERE:
# https://machinelearningmastery.com/display-deep-learning-model-training-history-in-keras/
# https://stackoverflow.com/questions/36952763/how-to-return-history-of-validation-loss-in-keras

training = pd.DataFrame.from_dict(hist.history)
training.plot(secondary_y=['acc', 'val_acc'])
Out[67]:
<matplotlib.axes._subplots.AxesSubplot at 0x7fae734e4860>

Load the Model with the Best Validation Loss

In [68]:
model.load_weights('saved_models/weights.best.from_scratch.hdf5')

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

In [69]:
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 9.5694%

Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

Obtain Bottleneck Features

In [70]:
bottleneck_features = np.load('/data/bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

In [71]:
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_3 ( (None, 512)               0         
_________________________________________________________________
dense_10 (Dense)             (None, 133)               68229     
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [72]:
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [73]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', 
                               verbose=1, save_best_only=True)

hist1 = VGG16_model.fit(train_VGG16, train_targets, 
          validation_data=(valid_VGG16, valid_targets),
          epochs=150, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/150
6520/6680 [============================>.] - ETA: 0s - loss: 12.9236 - acc: 0.0933Epoch 00001: val_loss improved from inf to 11.18567, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 3s 457us/step - loss: 12.8890 - acc: 0.0951 - val_loss: 11.1857 - val_acc: 0.1844
Epoch 2/150
6580/6680 [============================>.] - ETA: 0s - loss: 10.6078 - acc: 0.2467Epoch 00002: val_loss improved from 11.18567 to 10.39518, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 306us/step - loss: 10.6038 - acc: 0.2476 - val_loss: 10.3952 - val_acc: 0.2683
Epoch 3/150
6600/6680 [============================>.] - ETA: 0s - loss: 10.0989 - acc: 0.3130Epoch 00003: val_loss improved from 10.39518 to 10.17824, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 308us/step - loss: 10.0869 - acc: 0.3135 - val_loss: 10.1782 - val_acc: 0.2994
Epoch 4/150
6660/6680 [============================>.] - ETA: 0s - loss: 9.7399 - acc: 0.3505Epoch 00004: val_loss improved from 10.17824 to 9.97552, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 303us/step - loss: 9.7422 - acc: 0.3504 - val_loss: 9.9755 - val_acc: 0.3090
Epoch 5/150
6580/6680 [============================>.] - ETA: 0s - loss: 9.5021 - acc: 0.3688Epoch 00005: val_loss improved from 9.97552 to 9.87446, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 304us/step - loss: 9.4998 - acc: 0.3690 - val_loss: 9.8745 - val_acc: 0.3030
Epoch 6/150
6620/6680 [============================>.] - ETA: 0s - loss: 9.3469 - acc: 0.3858Epoch 00006: val_loss improved from 9.87446 to 9.82692, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 309us/step - loss: 9.3518 - acc: 0.3853 - val_loss: 9.8269 - val_acc: 0.3090
Epoch 7/150
6620/6680 [============================>.] - ETA: 0s - loss: 9.2432 - acc: 0.3974Epoch 00007: val_loss improved from 9.82692 to 9.58047, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 309us/step - loss: 9.2419 - acc: 0.3973 - val_loss: 9.5805 - val_acc: 0.3174
Epoch 8/150
6540/6680 [============================>.] - ETA: 0s - loss: 9.0449 - acc: 0.4089Epoch 00008: val_loss improved from 9.58047 to 9.37123, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 309us/step - loss: 9.0257 - acc: 0.4097 - val_loss: 9.3712 - val_acc: 0.3246
Epoch 9/150
6480/6680 [============================>.] - ETA: 0s - loss: 8.7965 - acc: 0.4307Epoch 00009: val_loss improved from 9.37123 to 9.35741, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 308us/step - loss: 8.7815 - acc: 0.4316 - val_loss: 9.3574 - val_acc: 0.3437
Epoch 10/150
6660/6680 [============================>.] - ETA: 0s - loss: 8.7269 - acc: 0.4416Epoch 00010: val_loss improved from 9.35741 to 9.17161, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 308us/step - loss: 8.7230 - acc: 0.4418 - val_loss: 9.1716 - val_acc: 0.3725
Epoch 11/150
6500/6680 [============================>.] - ETA: 0s - loss: 8.6295 - acc: 0.4486Epoch 00011: val_loss improved from 9.17161 to 9.12253, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 306us/step - loss: 8.6332 - acc: 0.4481 - val_loss: 9.1225 - val_acc: 0.3677
Epoch 12/150
6640/6680 [============================>.] - ETA: 0s - loss: 8.5773 - acc: 0.4581Epoch 00012: val_loss improved from 9.12253 to 9.11135, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 304us/step - loss: 8.5766 - acc: 0.4582 - val_loss: 9.1114 - val_acc: 0.3725
Epoch 13/150
6500/6680 [============================>.] - ETA: 0s - loss: 8.5341 - acc: 0.4588Epoch 00013: val_loss improved from 9.11135 to 8.99300, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 306us/step - loss: 8.5445 - acc: 0.4582 - val_loss: 8.9930 - val_acc: 0.3760
Epoch 14/150
6600/6680 [============================>.] - ETA: 0s - loss: 8.2834 - acc: 0.4689Epoch 00014: val_loss improved from 8.99300 to 8.75669, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 310us/step - loss: 8.2817 - acc: 0.4692 - val_loss: 8.7567 - val_acc: 0.3772
Epoch 15/150
6620/6680 [============================>.] - ETA: 0s - loss: 8.1037 - acc: 0.4822Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 2s 303us/step - loss: 8.0997 - acc: 0.4823 - val_loss: 8.7965 - val_acc: 0.3808
Epoch 16/150
6560/6680 [============================>.] - ETA: 0s - loss: 8.0414 - acc: 0.4896Epoch 00016: val_loss improved from 8.75669 to 8.65824, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 312us/step - loss: 8.0370 - acc: 0.4901 - val_loss: 8.6582 - val_acc: 0.3964
Epoch 17/150
6540/6680 [============================>.] - ETA: 0s - loss: 8.0047 - acc: 0.4917Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 2s 300us/step - loss: 7.9993 - acc: 0.4921 - val_loss: 8.6860 - val_acc: 0.3880
Epoch 18/150
6520/6680 [============================>.] - ETA: 0s - loss: 7.8758 - acc: 0.5012Epoch 00018: val_loss improved from 8.65824 to 8.54482, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 307us/step - loss: 7.8933 - acc: 0.5003 - val_loss: 8.5448 - val_acc: 0.4084
Epoch 19/150
6600/6680 [============================>.] - ETA: 0s - loss: 7.8306 - acc: 0.5048Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 2s 303us/step - loss: 7.8295 - acc: 0.5048 - val_loss: 8.6664 - val_acc: 0.3952
Epoch 20/150
6560/6680 [============================>.] - ETA: 0s - loss: 7.6333 - acc: 0.5139Epoch 00020: val_loss improved from 8.54482 to 8.35063, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 300us/step - loss: 7.6367 - acc: 0.5138 - val_loss: 8.3506 - val_acc: 0.4192
Epoch 21/150
6500/6680 [============================>.] - ETA: 0s - loss: 7.4683 - acc: 0.5283Epoch 00021: val_loss improved from 8.35063 to 8.25244, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 297us/step - loss: 7.5080 - acc: 0.5257 - val_loss: 8.2524 - val_acc: 0.4168
Epoch 22/150
6560/6680 [============================>.] - ETA: 0s - loss: 7.4253 - acc: 0.5279Epoch 00022: val_loss improved from 8.25244 to 8.13633, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 302us/step - loss: 7.4249 - acc: 0.5280 - val_loss: 8.1363 - val_acc: 0.4275
Epoch 23/150
6640/6680 [============================>.] - ETA: 0s - loss: 7.3111 - acc: 0.5352Epoch 00023: val_loss did not improve
6680/6680 [==============================] - 2s 301us/step - loss: 7.3111 - acc: 0.5352 - val_loss: 8.1697 - val_acc: 0.4204
Epoch 24/150
6520/6680 [============================>.] - ETA: 0s - loss: 7.1735 - acc: 0.5442Epoch 00024: val_loss improved from 8.13633 to 7.95231, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 301us/step - loss: 7.1656 - acc: 0.5445 - val_loss: 7.9523 - val_acc: 0.4395
Epoch 25/150
6620/6680 [============================>.] - ETA: 0s - loss: 7.0587 - acc: 0.5535Epoch 00025: val_loss did not improve
6680/6680 [==============================] - 2s 299us/step - loss: 7.0557 - acc: 0.5537 - val_loss: 7.9985 - val_acc: 0.4287
Epoch 26/150
6580/6680 [============================>.] - ETA: 0s - loss: 6.9892 - acc: 0.5565Epoch 00026: val_loss did not improve
6680/6680 [==============================] - 2s 298us/step - loss: 7.0222 - acc: 0.5543 - val_loss: 7.9869 - val_acc: 0.4228
Epoch 27/150
6560/6680 [============================>.] - ETA: 0s - loss: 6.9368 - acc: 0.5590Epoch 00027: val_loss improved from 7.95231 to 7.86332, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 301us/step - loss: 6.9305 - acc: 0.5594 - val_loss: 7.8633 - val_acc: 0.4419
Epoch 28/150
6560/6680 [============================>.] - ETA: 0s - loss: 6.8641 - acc: 0.5663Epoch 00028: val_loss improved from 7.86332 to 7.78793, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 301us/step - loss: 6.8829 - acc: 0.5651 - val_loss: 7.7879 - val_acc: 0.4419
Epoch 29/150
6600/6680 [============================>.] - ETA: 0s - loss: 6.8226 - acc: 0.5679Epoch 00029: val_loss improved from 7.78793 to 7.74122, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 300us/step - loss: 6.8038 - acc: 0.5690 - val_loss: 7.7412 - val_acc: 0.4479
Epoch 30/150
6580/6680 [============================>.] - ETA: 0s - loss: 6.7320 - acc: 0.5708Epoch 00030: val_loss improved from 7.74122 to 7.63606, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 314us/step - loss: 6.7211 - acc: 0.5716 - val_loss: 7.6361 - val_acc: 0.4563
Epoch 31/150
6500/6680 [============================>.] - ETA: 0s - loss: 6.6275 - acc: 0.5817Epoch 00031: val_loss did not improve
6680/6680 [==============================] - 2s 317us/step - loss: 6.6505 - acc: 0.5804 - val_loss: 7.6537 - val_acc: 0.4551
Epoch 32/150
6600/6680 [============================>.] - ETA: 0s - loss: 6.6128 - acc: 0.5848Epoch 00032: val_loss improved from 7.63606 to 7.62970, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 314us/step - loss: 6.6256 - acc: 0.5840 - val_loss: 7.6297 - val_acc: 0.4659
Epoch 33/150
6560/6680 [============================>.] - ETA: 0s - loss: 6.6317 - acc: 0.5840Epoch 00033: val_loss improved from 7.62970 to 7.59920, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 315us/step - loss: 6.6173 - acc: 0.5849 - val_loss: 7.5992 - val_acc: 0.4527
Epoch 34/150
6560/6680 [============================>.] - ETA: 0s - loss: 6.6241 - acc: 0.5857Epoch 00034: val_loss improved from 7.59920 to 7.56029, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 317us/step - loss: 6.6137 - acc: 0.5864 - val_loss: 7.5603 - val_acc: 0.4671
Epoch 35/150
6520/6680 [============================>.] - ETA: 0s - loss: 6.6035 - acc: 0.5871Epoch 00035: val_loss did not improve
6680/6680 [==============================] - 2s 316us/step - loss: 6.6072 - acc: 0.5870 - val_loss: 7.6667 - val_acc: 0.4587
Epoch 36/150
6500/6680 [============================>.] - ETA: 0s - loss: 6.4705 - acc: 0.5912Epoch 00036: val_loss improved from 7.56029 to 7.45922, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 319us/step - loss: 6.4971 - acc: 0.5897 - val_loss: 7.4592 - val_acc: 0.4671
Epoch 37/150
6520/6680 [============================>.] - ETA: 0s - loss: 6.4489 - acc: 0.5956Epoch 00037: val_loss improved from 7.45922 to 7.41948, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 317us/step - loss: 6.4328 - acc: 0.5964 - val_loss: 7.4195 - val_acc: 0.4754
Epoch 38/150
6520/6680 [============================>.] - ETA: 0s - loss: 6.4206 - acc: 0.5995Epoch 00038: val_loss did not improve
6680/6680 [==============================] - 2s 315us/step - loss: 6.4213 - acc: 0.5996 - val_loss: 7.4316 - val_acc: 0.4778
Epoch 39/150
6560/6680 [============================>.] - ETA: 0s - loss: 6.4503 - acc: 0.5983Epoch 00039: val_loss did not improve
6680/6680 [==============================] - 2s 312us/step - loss: 6.4190 - acc: 0.6003 - val_loss: 7.5318 - val_acc: 0.4731
Epoch 40/150
6560/6680 [============================>.] - ETA: 0s - loss: 6.4163 - acc: 0.6009Epoch 00040: val_loss did not improve
6680/6680 [==============================] - 2s 310us/step - loss: 6.4169 - acc: 0.6009 - val_loss: 7.4633 - val_acc: 0.4766
Epoch 41/150
6600/6680 [============================>.] - ETA: 0s - loss: 6.4017 - acc: 0.6015Epoch 00041: val_loss did not improve
6680/6680 [==============================] - 2s 310us/step - loss: 6.4168 - acc: 0.6006 - val_loss: 7.5168 - val_acc: 0.4766
Epoch 42/150
6520/6680 [============================>.] - ETA: 0s - loss: 6.3754 - acc: 0.6003Epoch 00042: val_loss improved from 7.41948 to 7.38968, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 313us/step - loss: 6.3612 - acc: 0.6012 - val_loss: 7.3897 - val_acc: 0.4838
Epoch 43/150
6540/6680 [============================>.] - ETA: 0s - loss: 6.2989 - acc: 0.6057Epoch 00043: val_loss improved from 7.38968 to 7.33993, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 314us/step - loss: 6.3171 - acc: 0.6045 - val_loss: 7.3399 - val_acc: 0.4862
Epoch 44/150
6560/6680 [============================>.] - ETA: 0s - loss: 6.2935 - acc: 0.6072Epoch 00044: val_loss did not improve
6680/6680 [==============================] - 2s 328us/step - loss: 6.2990 - acc: 0.6067 - val_loss: 7.3556 - val_acc: 0.4838
Epoch 45/150
6600/6680 [============================>.] - ETA: 0s - loss: 6.3041 - acc: 0.6071Epoch 00045: val_loss did not improve
6680/6680 [==============================] - 2s 335us/step - loss: 6.2942 - acc: 0.6076 - val_loss: 7.3743 - val_acc: 0.4826
Epoch 46/150
6520/6680 [============================>.] - ETA: 0s - loss: 6.2778 - acc: 0.6089Epoch 00046: val_loss did not improve
6680/6680 [==============================] - 2s 333us/step - loss: 6.2915 - acc: 0.6081 - val_loss: 7.3873 - val_acc: 0.4874
Epoch 47/150
6580/6680 [============================>.] - ETA: 0s - loss: 6.3104 - acc: 0.6074Epoch 00047: val_loss did not improve
6680/6680 [==============================] - 2s 339us/step - loss: 6.2908 - acc: 0.6087 - val_loss: 7.3576 - val_acc: 0.4922
Epoch 48/150
6580/6680 [============================>.] - ETA: 0s - loss: 6.2936 - acc: 0.6084Epoch 00048: val_loss did not improve
6680/6680 [==============================] - 2s 324us/step - loss: 6.2887 - acc: 0.6087 - val_loss: 7.3661 - val_acc: 0.4910
Epoch 49/150
6640/6680 [============================>.] - ETA: 0s - loss: 6.2879 - acc: 0.6078Epoch 00049: val_loss did not improve
6680/6680 [==============================] - 2s 308us/step - loss: 6.2842 - acc: 0.6079 - val_loss: 7.3449 - val_acc: 0.4970
Epoch 50/150
6540/6680 [============================>.] - ETA: 0s - loss: 6.2032 - acc: 0.6102Epoch 00050: val_loss did not improve
6680/6680 [==============================] - 2s 311us/step - loss: 6.2230 - acc: 0.6090 - val_loss: 7.3645 - val_acc: 0.4754
Epoch 51/150
6600/6680 [============================>.] - ETA: 0s - loss: 6.1841 - acc: 0.6132Epoch 00051: val_loss improved from 7.33993 to 7.32304, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 309us/step - loss: 6.1634 - acc: 0.6144 - val_loss: 7.3230 - val_acc: 0.4934
Epoch 52/150
6660/6680 [============================>.] - ETA: 0s - loss: 6.1504 - acc: 0.6161Epoch 00052: val_loss did not improve
6680/6680 [==============================] - 2s 302us/step - loss: 6.1440 - acc: 0.6165 - val_loss: 7.3823 - val_acc: 0.4826
Epoch 53/150
6660/6680 [============================>.] - ETA: 0s - loss: 6.1208 - acc: 0.6162Epoch 00053: val_loss did not improve
6680/6680 [==============================] - 2s 305us/step - loss: 6.1290 - acc: 0.6157 - val_loss: 7.4377 - val_acc: 0.4754
Epoch 54/150
6560/6680 [============================>.] - ETA: 0s - loss: 6.1017 - acc: 0.6162Epoch 00054: val_loss did not improve
6680/6680 [==============================] - 2s 313us/step - loss: 6.0840 - acc: 0.6172 - val_loss: 7.3531 - val_acc: 0.4898
Epoch 55/150
6660/6680 [============================>.] - ETA: 0s - loss: 6.0572 - acc: 0.6188Epoch 00055: val_loss did not improve
6680/6680 [==============================] - 2s 317us/step - loss: 6.0450 - acc: 0.6193 - val_loss: 7.3763 - val_acc: 0.4886
Epoch 56/150
6560/6680 [============================>.] - ETA: 0s - loss: 6.0034 - acc: 0.6212Epoch 00056: val_loss did not improve
6680/6680 [==============================] - 2s 313us/step - loss: 6.0175 - acc: 0.6202 - val_loss: 7.3351 - val_acc: 0.4886
Epoch 57/150
6560/6680 [============================>.] - ETA: 0s - loss: 5.9852 - acc: 0.6238Epoch 00057: val_loss did not improve
6680/6680 [==============================] - 2s 311us/step - loss: 5.9963 - acc: 0.6231 - val_loss: 7.3463 - val_acc: 0.4862
Epoch 58/150
6580/6680 [============================>.] - ETA: 0s - loss: 5.9915 - acc: 0.6239Epoch 00058: val_loss did not improve
6680/6680 [==============================] - 2s 319us/step - loss: 5.9815 - acc: 0.6246 - val_loss: 7.3593 - val_acc: 0.4838
Epoch 59/150
6500/6680 [============================>.] - ETA: 0s - loss: 5.9799 - acc: 0.6251Epoch 00059: val_loss did not improve
6680/6680 [==============================] - 2s 317us/step - loss: 5.9783 - acc: 0.6251 - val_loss: 7.3920 - val_acc: 0.4922
Epoch 60/150
6660/6680 [============================>.] - ETA: 0s - loss: 5.9675 - acc: 0.6264Epoch 00060: val_loss improved from 7.32304 to 7.30859, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 318us/step - loss: 5.9738 - acc: 0.6260 - val_loss: 7.3086 - val_acc: 0.5006
Epoch 61/150
6620/6680 [============================>.] - ETA: 0s - loss: 5.9647 - acc: 0.6267Epoch 00061: val_loss improved from 7.30859 to 7.29911, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 310us/step - loss: 5.9666 - acc: 0.6266 - val_loss: 7.2991 - val_acc: 0.4946
Epoch 62/150
6500/6680 [============================>.] - ETA: 0s - loss: 5.9545 - acc: 0.6280Epoch 00062: val_loss improved from 7.29911 to 7.27680, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 311us/step - loss: 5.9630 - acc: 0.6275 - val_loss: 7.2768 - val_acc: 0.4970
Epoch 63/150
6560/6680 [============================>.] - ETA: 0s - loss: 5.9523 - acc: 0.6296Epoch 00063: val_loss did not improve
6680/6680 [==============================] - 2s 309us/step - loss: 5.9612 - acc: 0.6290 - val_loss: 7.3590 - val_acc: 0.4898
Epoch 64/150
6660/6680 [============================>.] - ETA: 0s - loss: 5.9709 - acc: 0.6278Epoch 00064: val_loss did not improve
6680/6680 [==============================] - 2s 307us/step - loss: 5.9603 - acc: 0.6284 - val_loss: 7.3309 - val_acc: 0.4958
Epoch 65/150
6600/6680 [============================>.] - ETA: 0s - loss: 5.9625 - acc: 0.6288Epoch 00065: val_loss did not improve
6680/6680 [==============================] - 2s 309us/step - loss: 5.9610 - acc: 0.6289 - val_loss: 7.3616 - val_acc: 0.4826
Epoch 66/150
6540/6680 [============================>.] - ETA: 0s - loss: 5.9467 - acc: 0.6295Epoch 00066: val_loss improved from 7.27680 to 7.25225, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 314us/step - loss: 5.9596 - acc: 0.6287 - val_loss: 7.2522 - val_acc: 0.4910
Epoch 67/150
6620/6680 [============================>.] - ETA: 0s - loss: 5.9695 - acc: 0.6285Epoch 00067: val_loss did not improve
6680/6680 [==============================] - 2s 311us/step - loss: 5.9593 - acc: 0.6292 - val_loss: 7.3240 - val_acc: 0.4922
Epoch 68/150
6540/6680 [============================>.] - ETA: 0s - loss: 5.9504 - acc: 0.6300Epoch 00068: val_loss did not improve
6680/6680 [==============================] - 2s 312us/step - loss: 5.9573 - acc: 0.6295 - val_loss: 7.3583 - val_acc: 0.4850
Epoch 69/150
6580/6680 [============================>.] - ETA: 0s - loss: 5.9648 - acc: 0.6292Epoch 00069: val_loss did not improve
6680/6680 [==============================] - 2s 311us/step - loss: 5.9552 - acc: 0.6298 - val_loss: 7.3245 - val_acc: 0.4862
Epoch 70/150
6620/6680 [============================>.] - ETA: 0s - loss: 5.9554 - acc: 0.6295Epoch 00070: val_loss did not improve
6680/6680 [==============================] - 2s 310us/step - loss: 5.9550 - acc: 0.6295 - val_loss: 7.3518 - val_acc: 0.4934
Epoch 71/150
6600/6680 [============================>.] - ETA: 0s - loss: 5.9602 - acc: 0.6294Epoch 00071: val_loss did not improve
6680/6680 [==============================] - 2s 308us/step - loss: 5.9564 - acc: 0.6296 - val_loss: 7.3488 - val_acc: 0.4826
Epoch 72/150
6520/6680 [============================>.] - ETA: 0s - loss: 5.9624 - acc: 0.6293Epoch 00072: val_loss did not improve
6680/6680 [==============================] - 2s 312us/step - loss: 5.9523 - acc: 0.6299 - val_loss: 7.3766 - val_acc: 0.4886
Epoch 73/150
6560/6680 [============================>.] - ETA: 0s - loss: 5.9681 - acc: 0.6290Epoch 00073: val_loss did not improve
6680/6680 [==============================] - 2s 310us/step - loss: 5.9574 - acc: 0.6296 - val_loss: 7.3557 - val_acc: 0.4922
Epoch 74/150
6660/6680 [============================>.] - ETA: 0s - loss: 5.9541 - acc: 0.6305Epoch 00074: val_loss did not improve
6680/6680 [==============================] - 2s 316us/step - loss: 5.9556 - acc: 0.6304 - val_loss: 7.3438 - val_acc: 0.4934
Epoch 75/150
6620/6680 [============================>.] - ETA: 0s - loss: 5.9613 - acc: 0.6295Epoch 00075: val_loss did not improve
6680/6680 [==============================] - 2s 319us/step - loss: 5.9560 - acc: 0.6298 - val_loss: 7.3743 - val_acc: 0.4958
Epoch 76/150
6500/6680 [============================>.] - ETA: 0s - loss: 5.9500 - acc: 0.6306Epoch 00076: val_loss did not improve
6680/6680 [==============================] - 2s 314us/step - loss: 5.9585 - acc: 0.6301 - val_loss: 7.3741 - val_acc: 0.4850
Epoch 77/150
6580/6680 [============================>.] - ETA: 0s - loss: 5.9602 - acc: 0.6298Epoch 00077: val_loss did not improve
6680/6680 [==============================] - 2s 309us/step - loss: 5.9554 - acc: 0.6301 - val_loss: 7.3611 - val_acc: 0.4874
Epoch 78/150
6580/6680 [============================>.] - ETA: 0s - loss: 5.9573 - acc: 0.6298Epoch 00078: val_loss did not improve
6680/6680 [==============================] - 2s 311us/step - loss: 5.9574 - acc: 0.6298 - val_loss: 7.3944 - val_acc: 0.4886
Epoch 79/150
6560/6680 [============================>.] - ETA: 0s - loss: 5.9491 - acc: 0.6303Epoch 00079: val_loss did not improve
6680/6680 [==============================] - 2s 312us/step - loss: 5.9556 - acc: 0.6299 - val_loss: 7.3405 - val_acc: 0.4874
Epoch 80/150
6580/6680 [============================>.] - ETA: 0s - loss: 5.9663 - acc: 0.6296Epoch 00080: val_loss did not improve
6680/6680 [==============================] - 2s 312us/step - loss: 5.9542 - acc: 0.6304 - val_loss: 7.3346 - val_acc: 0.4886
Epoch 81/150
6560/6680 [============================>.] - ETA: 0s - loss: 5.9587 - acc: 0.6299Epoch 00081: val_loss did not improve
6680/6680 [==============================] - 2s 312us/step - loss: 5.9537 - acc: 0.6301 - val_loss: 7.3368 - val_acc: 0.4910
Epoch 82/150
6500/6680 [============================>.] - ETA: 0s - loss: 5.9497 - acc: 0.6303Epoch 00082: val_loss did not improve
6680/6680 [==============================] - 2s 301us/step - loss: 5.9535 - acc: 0.6301 - val_loss: 7.3914 - val_acc: 0.4838
Epoch 83/150
6480/6680 [============================>.] - ETA: 0s - loss: 5.9646 - acc: 0.6293Epoch 00083: val_loss did not improve
6680/6680 [==============================] - 2s 300us/step - loss: 5.9549 - acc: 0.6299 - val_loss: 7.3458 - val_acc: 0.4910
Epoch 84/150
6640/6680 [============================>.] - ETA: 0s - loss: 5.9488 - acc: 0.6301Epoch 00084: val_loss did not improve
6680/6680 [==============================] - 2s 308us/step - loss: 5.9518 - acc: 0.6299 - val_loss: 7.3508 - val_acc: 0.4946
Epoch 85/150
6560/6680 [============================>.] - ETA: 0s - loss: 5.9775 - acc: 0.6287Epoch 00085: val_loss did not improve
6680/6680 [==============================] - 2s 312us/step - loss: 5.9522 - acc: 0.6302 - val_loss: 7.3012 - val_acc: 0.4898
Epoch 86/150
6640/6680 [============================>.] - ETA: 0s - loss: 5.9644 - acc: 0.6294Epoch 00086: val_loss did not improve
6680/6680 [==============================] - 2s 307us/step - loss: 5.9528 - acc: 0.6301 - val_loss: 7.3665 - val_acc: 0.4862
Epoch 87/150
6660/6680 [============================>.] - ETA: 0s - loss: 5.9519 - acc: 0.6302Epoch 00087: val_loss did not improve
6680/6680 [==============================] - 2s 304us/step - loss: 5.9534 - acc: 0.6301 - val_loss: 7.3471 - val_acc: 0.4898
Epoch 88/150
6560/6680 [============================>.] - ETA: 0s - loss: 5.9601 - acc: 0.6294Epoch 00088: val_loss did not improve
6680/6680 [==============================] - 2s 305us/step - loss: 5.9520 - acc: 0.6299 - val_loss: 7.3395 - val_acc: 0.4946
Epoch 89/150
6620/6680 [============================>.] - ETA: 0s - loss: 5.9514 - acc: 0.6304Epoch 00089: val_loss did not improve
6680/6680 [==============================] - 2s 305us/step - loss: 5.9510 - acc: 0.6304 - val_loss: 7.3877 - val_acc: 0.4850
Epoch 90/150
6600/6680 [============================>.] - ETA: 0s - loss: 5.9695 - acc: 0.6291Epoch 00090: val_loss did not improve
6680/6680 [==============================] - 2s 309us/step - loss: 5.9535 - acc: 0.6301 - val_loss: 7.3095 - val_acc: 0.4862
Epoch 91/150
6580/6680 [============================>.] - ETA: 0s - loss: 5.9472 - acc: 0.6309Epoch 00091: val_loss did not improve
6680/6680 [==============================] - 2s 310us/step - loss: 5.9523 - acc: 0.6305 - val_loss: 7.3256 - val_acc: 0.4850
Epoch 92/150
6660/6680 [============================>.] - ETA: 0s - loss: 5.9512 - acc: 0.6303Epoch 00092: val_loss did not improve
6680/6680 [==============================] - 2s 308us/step - loss: 5.9527 - acc: 0.6302 - val_loss: 7.3259 - val_acc: 0.4910
Epoch 93/150
6600/6680 [============================>.] - ETA: 0s - loss: 5.9470 - acc: 0.6305Epoch 00093: val_loss did not improve
6680/6680 [==============================] - 2s 310us/step - loss: 5.9505 - acc: 0.6302 - val_loss: 7.3375 - val_acc: 0.4958
Epoch 94/150
6600/6680 [============================>.] - ETA: 0s - loss: 5.9406 - acc: 0.6309Epoch 00094: val_loss did not improve
6680/6680 [==============================] - 2s 310us/step - loss: 5.9515 - acc: 0.6302 - val_loss: 7.3408 - val_acc: 0.4922
Epoch 95/150
6560/6680 [============================>.] - ETA: 0s - loss: 5.9473 - acc: 0.6305Epoch 00095: val_loss did not improve
6680/6680 [==============================] - 2s 309us/step - loss: 5.9515 - acc: 0.6302 - val_loss: 7.3953 - val_acc: 0.4886
Epoch 96/150
6520/6680 [============================>.] - ETA: 0s - loss: 5.9515 - acc: 0.6304Epoch 00096: val_loss did not improve
6680/6680 [==============================] - 2s 312us/step - loss: 5.9513 - acc: 0.6304 - val_loss: 7.3503 - val_acc: 0.4910
Epoch 97/150
6560/6680 [============================>.] - ETA: 0s - loss: 5.9501 - acc: 0.6305Epoch 00097: val_loss did not improve
6680/6680 [==============================] - 2s 311us/step - loss: 5.9494 - acc: 0.6305 - val_loss: 7.3630 - val_acc: 0.4862
Epoch 98/150
6600/6680 [============================>.] - ETA: 0s - loss: 5.9449 - acc: 0.6308Epoch 00098: val_loss did not improve
6680/6680 [==============================] - 2s 308us/step - loss: 5.9533 - acc: 0.6302 - val_loss: 7.3491 - val_acc: 0.4862
Epoch 99/150
6560/6680 [============================>.] - ETA: 0s - loss: 5.9500 - acc: 0.6308Epoch 00099: val_loss did not improve
6680/6680 [==============================] - 2s 309us/step - loss: 5.9517 - acc: 0.6307 - val_loss: 7.3648 - val_acc: 0.4862
Epoch 100/150
6580/6680 [============================>.] - ETA: 0s - loss: 5.9687 - acc: 0.6292Epoch 00100: val_loss did not improve
6680/6680 [==============================] - 2s 309us/step - loss: 5.9517 - acc: 0.6302 - val_loss: 7.3499 - val_acc: 0.4958
Epoch 101/150
6620/6680 [============================>.] - ETA: 0s - loss: 5.9380 - acc: 0.6313Epoch 00101: val_loss did not improve
6680/6680 [==============================] - 2s 312us/step - loss: 5.9522 - acc: 0.6304 - val_loss: 7.3558 - val_acc: 0.4910
Epoch 102/150
6500/6680 [============================>.] - ETA: 0s - loss: 5.9677 - acc: 0.6294Epoch 00102: val_loss did not improve
6680/6680 [==============================] - 2s 318us/step - loss: 5.9516 - acc: 0.6304 - val_loss: 7.3633 - val_acc: 0.4922
Epoch 103/150
6640/6680 [============================>.] - ETA: 0s - loss: 5.9544 - acc: 0.6301Epoch 00103: val_loss did not improve
6680/6680 [==============================] - 2s 318us/step - loss: 5.9525 - acc: 0.6302 - val_loss: 7.3510 - val_acc: 0.4910
Epoch 104/150
6560/6680 [============================>.] - ETA: 0s - loss: 5.9687 - acc: 0.6294Epoch 00104: val_loss did not improve
6680/6680 [==============================] - 2s 300us/step - loss: 5.9508 - acc: 0.6305 - val_loss: 7.3753 - val_acc: 0.4922
Epoch 105/150
6660/6680 [============================>.] - ETA: 0s - loss: 5.9583 - acc: 0.6300Epoch 00105: val_loss did not improve
6680/6680 [==============================] - 2s 300us/step - loss: 5.9501 - acc: 0.6305 - val_loss: 7.3368 - val_acc: 0.4934
Epoch 106/150
6500/6680 [============================>.] - ETA: 0s - loss: 5.9560 - acc: 0.6302Epoch 00106: val_loss did not improve
6680/6680 [==============================] - 2s 297us/step - loss: 5.9499 - acc: 0.6305 - val_loss: 7.3719 - val_acc: 0.4850
Epoch 107/150
6660/6680 [============================>.] - ETA: 0s - loss: 5.9469 - acc: 0.6308Epoch 00107: val_loss did not improve
6680/6680 [==============================] - 2s 295us/step - loss: 5.9508 - acc: 0.6305 - val_loss: 7.3376 - val_acc: 0.4874
Epoch 108/150
6560/6680 [============================>.] - ETA: 0s - loss: 5.9606 - acc: 0.6300Epoch 00108: val_loss did not improve
6680/6680 [==============================] - 2s 292us/step - loss: 5.9501 - acc: 0.6307 - val_loss: 7.3932 - val_acc: 0.4874
Epoch 109/150
6480/6680 [============================>.] - ETA: 0s - loss: 5.9341 - acc: 0.6313Epoch 00109: val_loss did not improve
6680/6680 [==============================] - 2s 293us/step - loss: 5.9519 - acc: 0.6302 - val_loss: 7.3741 - val_acc: 0.4862
Epoch 110/150
6600/6680 [============================>.] - ETA: 0s - loss: 5.9523 - acc: 0.6303Epoch 00110: val_loss did not improve
6680/6680 [==============================] - 2s 303us/step - loss: 5.9510 - acc: 0.6304 - val_loss: 7.3483 - val_acc: 0.4910
Epoch 111/150
6640/6680 [============================>.] - ETA: 0s - loss: 5.9465 - acc: 0.6309Epoch 00111: val_loss did not improve
6680/6680 [==============================] - 2s 308us/step - loss: 5.9495 - acc: 0.6307 - val_loss: 7.3880 - val_acc: 0.4826
Epoch 112/150
6520/6680 [============================>.] - ETA: 0s - loss: 5.9602 - acc: 0.6299Epoch 00112: val_loss did not improve
6680/6680 [==============================] - 2s 308us/step - loss: 5.9503 - acc: 0.6304 - val_loss: 7.3653 - val_acc: 0.4898
Epoch 113/150
6640/6680 [============================>.] - ETA: 0s - loss: 5.9477 - acc: 0.6306Epoch 00113: val_loss did not improve
6680/6680 [==============================] - 2s 311us/step - loss: 5.9506 - acc: 0.6304 - val_loss: 7.3584 - val_acc: 0.4886
Epoch 114/150
6500/6680 [============================>.] - ETA: 0s - loss: 5.9635 - acc: 0.6298Epoch 00114: val_loss did not improve
6680/6680 [==============================] - 2s 307us/step - loss: 5.9500 - acc: 0.6307 - val_loss: 7.3771 - val_acc: 0.4850
Epoch 115/150
6620/6680 [============================>.] - ETA: 0s - loss: 5.9465 - acc: 0.6307Epoch 00115: val_loss did not improve
6680/6680 [==============================] - 2s 298us/step - loss: 5.9510 - acc: 0.6304 - val_loss: 7.3484 - val_acc: 0.4862
Epoch 116/150
6580/6680 [============================>.] - ETA: 0s - loss: 5.9436 - acc: 0.6310Epoch 00116: val_loss did not improve
6680/6680 [==============================] - 2s 310us/step - loss: 5.9511 - acc: 0.6305 - val_loss: 7.3733 - val_acc: 0.4898
Epoch 117/150
6620/6680 [============================>.] - ETA: 0s - loss: 5.9590 - acc: 0.6301Epoch 00117: val_loss did not improve
6680/6680 [==============================] - 2s 300us/step - loss: 5.9514 - acc: 0.6305 - val_loss: 7.3737 - val_acc: 0.4874
Epoch 118/150
6640/6680 [============================>.] - ETA: 0s - loss: 5.9492 - acc: 0.6307Epoch 00118: val_loss did not improve
6680/6680 [==============================] - 2s 294us/step - loss: 5.9522 - acc: 0.6305 - val_loss: 7.3830 - val_acc: 0.4922
Epoch 119/150
6640/6680 [============================>.] - ETA: 0s - loss: 5.9496 - acc: 0.6306Epoch 00119: val_loss did not improve
6680/6680 [==============================] - 2s 301us/step - loss: 5.9515 - acc: 0.6304 - val_loss: 7.3704 - val_acc: 0.4898
Epoch 120/150
6540/6680 [============================>.] - ETA: 0s - loss: 5.9498 - acc: 0.6306Epoch 00120: val_loss did not improve
6680/6680 [==============================] - 2s 298us/step - loss: 5.9506 - acc: 0.6305 - val_loss: 7.3768 - val_acc: 0.4898
Epoch 121/150
6600/6680 [============================>.] - ETA: 0s - loss: 5.9370 - acc: 0.6314Epoch 00121: val_loss did not improve
6680/6680 [==============================] - 2s 296us/step - loss: 5.9504 - acc: 0.6305 - val_loss: 7.3629 - val_acc: 0.4898
Epoch 122/150
6640/6680 [============================>.] - ETA: 0s - loss: 5.9722 - acc: 0.6292Epoch 00122: val_loss did not improve
6680/6680 [==============================] - 2s 301us/step - loss: 5.9485 - acc: 0.6307 - val_loss: 7.4044 - val_acc: 0.4838
Epoch 123/150
6660/6680 [============================>.] - ETA: 0s - loss: 5.9628 - acc: 0.6299Epoch 00123: val_loss did not improve
6680/6680 [==============================] - 2s 301us/step - loss: 5.9522 - acc: 0.6305 - val_loss: 7.3710 - val_acc: 0.4910
Epoch 124/150
6500/6680 [============================>.] - ETA: 0s - loss: 5.9572 - acc: 0.6303Epoch 00124: val_loss did not improve
6680/6680 [==============================] - 2s 300us/step - loss: 5.9492 - acc: 0.6307 - val_loss: 7.3746 - val_acc: 0.4814
Epoch 125/150
6520/6680 [============================>.] - ETA: 0s - loss: 5.9518 - acc: 0.6305Epoch 00125: val_loss did not improve
6680/6680 [==============================] - 2s 305us/step - loss: 5.9516 - acc: 0.6305 - val_loss: 7.3810 - val_acc: 0.4826
Epoch 126/150
6600/6680 [============================>.] - ETA: 0s - loss: 5.9558 - acc: 0.6302Epoch 00126: val_loss did not improve
6680/6680 [==============================] - 2s 302us/step - loss: 5.9520 - acc: 0.6304 - val_loss: 7.3812 - val_acc: 0.4874
Epoch 127/150
6660/6680 [============================>.] - ETA: 0s - loss: 5.9470 - acc: 0.6308Epoch 00127: val_loss did not improve
6680/6680 [==============================] - 2s 301us/step - loss: 5.9509 - acc: 0.6305 - val_loss: 7.3582 - val_acc: 0.4886
Epoch 128/150
6500/6680 [============================>.] - ETA: 0s - loss: 5.9478 - acc: 0.6308Epoch 00128: val_loss did not improve
6680/6680 [==============================] - 2s 300us/step - loss: 5.9516 - acc: 0.6305 - val_loss: 7.3636 - val_acc: 0.4922
Epoch 129/150
6520/6680 [============================>.] - ETA: 0s - loss: 5.9647 - acc: 0.6294Epoch 00129: val_loss did not improve
6680/6680 [==============================] - 2s 299us/step - loss: 5.9522 - acc: 0.6302 - val_loss: 7.3350 - val_acc: 0.4886
Epoch 130/150
6640/6680 [============================>.] - ETA: 0s - loss: 5.9548 - acc: 0.6303Epoch 00130: val_loss did not improve
6680/6680 [==============================] - 2s 295us/step - loss: 5.9529 - acc: 0.6304 - val_loss: 7.3489 - val_acc: 0.4898
Epoch 131/150
6660/6680 [============================>.] - ETA: 0s - loss: 5.9447 - acc: 0.6309Epoch 00131: val_loss did not improve
6680/6680 [==============================] - 2s 300us/step - loss: 5.9511 - acc: 0.6305 - val_loss: 7.3476 - val_acc: 0.4886
Epoch 132/150
6540/6680 [============================>.] - ETA: 0s - loss: 5.9678 - acc: 0.6295Epoch 00132: val_loss did not improve
6680/6680 [==============================] - 2s 299us/step - loss: 5.9513 - acc: 0.6305 - val_loss: 7.3346 - val_acc: 0.4874
Epoch 133/150
6580/6680 [============================>.] - ETA: 0s - loss: 5.9469 - acc: 0.6307Epoch 00133: val_loss did not improve
6680/6680 [==============================] - 2s 296us/step - loss: 5.9520 - acc: 0.6304 - val_loss: 7.3326 - val_acc: 0.4862
Epoch 134/150
6580/6680 [============================>.] - ETA: 0s - loss: 5.9690 - acc: 0.6295Epoch 00134: val_loss did not improve
6680/6680 [==============================] - 2s 299us/step - loss: 5.9520 - acc: 0.6305 - val_loss: 7.3556 - val_acc: 0.4838
Epoch 135/150
6660/6680 [============================>.] - ETA: 0s - loss: 5.9530 - acc: 0.6303Epoch 00135: val_loss did not improve
6680/6680 [==============================] - 2s 301us/step - loss: 5.9521 - acc: 0.6304 - val_loss: 7.3526 - val_acc: 0.4850
Epoch 136/150
6520/6680 [============================>.] - ETA: 0s - loss: 5.9483 - acc: 0.6305Epoch 00136: val_loss did not improve
6680/6680 [==============================] - 2s 300us/step - loss: 5.9506 - acc: 0.6304 - val_loss: 7.3512 - val_acc: 0.4910
Epoch 137/150
6640/6680 [============================>.] - ETA: 0s - loss: 5.9560 - acc: 0.6303Epoch 00137: val_loss did not improve
6680/6680 [==============================] - 2s 303us/step - loss: 5.9517 - acc: 0.6305 - val_loss: 7.3621 - val_acc: 0.4922
Epoch 138/150
6660/6680 [============================>.] - ETA: 0s - loss: 5.9548 - acc: 0.6303Epoch 00138: val_loss did not improve
6680/6680 [==============================] - 2s 301us/step - loss: 5.9515 - acc: 0.6305 - val_loss: 7.4094 - val_acc: 0.4886
Epoch 139/150
6660/6680 [============================>.] - ETA: 0s - loss: 5.9511 - acc: 0.6305Epoch 00139: val_loss did not improve
6680/6680 [==============================] - 2s 303us/step - loss: 5.9502 - acc: 0.6305 - val_loss: 7.3848 - val_acc: 0.4898
Epoch 140/150
6620/6680 [============================>.] - ETA: 0s - loss: 5.9524 - acc: 0.6304Epoch 00140: val_loss did not improve
6680/6680 [==============================] - 2s 295us/step - loss: 5.9520 - acc: 0.6304 - val_loss: 7.3648 - val_acc: 0.4898
Epoch 141/150
6560/6680 [============================>.] - ETA: 0s - loss: 5.9633 - acc: 0.6296Epoch 00141: val_loss did not improve
6680/6680 [==============================] - 2s 296us/step - loss: 5.9526 - acc: 0.6302 - val_loss: 7.3702 - val_acc: 0.4874
Epoch 142/150
6540/6680 [============================>.] - ETA: 0s - loss: 5.9504 - acc: 0.6306Epoch 00142: val_loss did not improve
6680/6680 [==============================] - 2s 300us/step - loss: 5.9512 - acc: 0.6305 - val_loss: 7.4204 - val_acc: 0.4850
Epoch 143/150
6480/6680 [============================>.] - ETA: 0s - loss: 5.9834 - acc: 0.6287Epoch 00143: val_loss did not improve
6680/6680 [==============================] - 2s 299us/step - loss: 5.9514 - acc: 0.6307 - val_loss: 7.3537 - val_acc: 0.4910
Epoch 144/150
6560/6680 [============================>.] - ETA: 0s - loss: 5.9600 - acc: 0.6300Epoch 00144: val_loss did not improve
6680/6680 [==============================] - 2s 299us/step - loss: 5.9519 - acc: 0.6305 - val_loss: 7.3679 - val_acc: 0.4874
Epoch 145/150
6480/6680 [============================>.] - ETA: 0s - loss: 5.9298 - acc: 0.6318Epoch 00145: val_loss did not improve
6680/6680 [==============================] - 2s 298us/step - loss: 5.9520 - acc: 0.6304 - val_loss: 7.3777 - val_acc: 0.4802
Epoch 146/150
6540/6680 [============================>.] - ETA: 0s - loss: 5.9281 - acc: 0.6320Epoch 00146: val_loss did not improve
6680/6680 [==============================] - 2s 305us/step - loss: 5.9511 - acc: 0.6305 - val_loss: 7.3370 - val_acc: 0.4922
Epoch 147/150
6500/6680 [============================>.] - ETA: 0s - loss: 5.9414 - acc: 0.6312Epoch 00147: val_loss did not improve
6680/6680 [==============================] - 2s 300us/step - loss: 5.9502 - acc: 0.6307 - val_loss: 7.3932 - val_acc: 0.4886
Epoch 148/150
6580/6680 [============================>.] - ETA: 0s - loss: 5.9387 - acc: 0.6315Epoch 00148: val_loss did not improve
6680/6680 [==============================] - 2s 303us/step - loss: 5.9511 - acc: 0.6307 - val_loss: 7.3775 - val_acc: 0.4838
Epoch 149/150
6480/6680 [============================>.] - ETA: 0s - loss: 5.9032 - acc: 0.6333Epoch 00149: val_loss did not improve
6680/6680 [==============================] - 2s 303us/step - loss: 5.9508 - acc: 0.6304 - val_loss: 7.3786 - val_acc: 0.4850
Epoch 150/150
6600/6680 [============================>.] - ETA: 0s - loss: 5.9534 - acc: 0.6305Epoch 00150: val_loss did not improve
6680/6680 [==============================] - 2s 297us/step - loss: 5.9521 - acc: 0.6305 - val_loss: 7.3681 - val_acc: 0.4826
In [74]:
training1 = pd.DataFrame.from_dict(hist1.history)
training1.plot(secondary_y=['acc', 'val_acc'])
Out[74]:
<matplotlib.axes._subplots.AxesSubplot at 0x7fae4b10b978>

Load the Model with the Best Validation Loss

In [75]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

In [76]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 48.6842%

Predict Dog Breed with the Model

In [77]:
from extract_bottleneck_features import *

def VGG16_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG16_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras. These are already in the workspace, at /data/bottleneck_features. If you wish to download them on a different machine, they can be found at:

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception.

The above architectures are downloaded and stored for you in the /data/bottleneck_features/ folder.

This means the following will be in the /data/bottleneck_features/ folder:

DogVGG19Data.npz DogResnet50Data.npz DogInceptionV3Data.npz DogXceptionData.npz

(IMPLEMENTATION) Obtain Bottleneck Features

In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('/data/bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
In [78]:
### TODO: Obtain bottleneck features from another pre-trained CNN.

bottleneck_features = np.load('/data/bottleneck_features/DogResnet50Data.npz')
train_Resnet50 = bottleneck_features['train']
valid_Resnet50 = bottleneck_features['valid']
test_Resnet50 = bottleneck_features['test']

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    <your model's name>.summary()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer:

  • I have chosen Resnet50 to conduct the transfer learning. When I first selected it, I honestly didn't even think about why one would be better than the other. I had chosen Resnet50. After now doing some research, I'm thinking I'd have chosen the Xception model as it seems to perform even better than Resnet50 and InceptionV3. See ref below.

https://towardsdatascience.com/review-xception-with-depthwise-separable-convolution-better-than-inception-v3-image-dc967dd42568

  • It's likely that Resnet50 will significantly outperform my clunky model above as it's been designed specifically for the purpose of image classification by a leading team of experts. Additionally, it uses many more hidden layers that have been carefully designed and implemented for this purpose. It has also already been pre-trained on a much larger training set which includes dogs.

  • In order to arrive at this architecture I started with just the GlobalAveragePooling layer and the Dense layer with softmax activation. From there I have experimented with Substituting the GlobalAveragePooling for MaxPooling, adding in a fully connected dense layer of varying size (256 -> 1024) and adding an aggressive Dropout layer to help reduce overfitting on the training set.

  • It's no longer shown in the code but I had attemped to augment the training set but I was struggling to implement this correctly. I was hopeful that could boost my performance from 75-80% to 90+%. Alas I could not get this implemented.
In [99]:
### TODO: Define your architecture.

Resnet50_model = Sequential()
#Resnet50_model.add(GlobalAveragePooling2D(input_shape=train_Resnet50.shape[1:]))
Resnet50_model.add(MaxPooling2D(input_shape=train_Resnet50.shape[1:],pool_size=1))
Resnet50_model.add(Flatten())
#Resnet50_model.add(Dense(1024))
#Resnet50_model.add(Dropout(0.5))
Resnet50_model.add(Dense(133, activation='softmax'))

Resnet50_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
max_pooling2d_22 (MaxPooling (None, 1, 1, 2048)        0         
_________________________________________________________________
flatten_9 (Flatten)          (None, 2048)              0         
_________________________________________________________________
dense_18 (Dense)             (None, 133)               272517    
=================================================================
Total params: 272,517
Trainable params: 272,517
Non-trainable params: 0
_________________________________________________________________

(IMPLEMENTATION) Compile the Model

In [97]:
### TODO: Compile the model.

Resnet50_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [98]:
from keras.preprocessing.image import ImageDataGenerator

### TODO: Train the model.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.Resnet50.hdf5', 
                               verbose=1, save_best_only=True)

hist2 = Resnet50_model.fit(train_Resnet50, train_targets, 
          validation_data=(valid_Resnet50, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6480/6680 [============================>.] - ETA: 0s - loss: 1.6340 - acc: 0.6037Epoch 00001: val_loss improved from inf to 0.85923, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 3s 467us/step - loss: 1.6077 - acc: 0.6097 - val_loss: 0.8592 - val_acc: 0.7257
Epoch 2/20
6460/6680 [============================>.] - ETA: 0s - loss: 0.4342 - acc: 0.8610Epoch 00002: val_loss improved from 0.85923 to 0.72556, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 2s 279us/step - loss: 0.4395 - acc: 0.8597 - val_loss: 0.7256 - val_acc: 0.7796
Epoch 3/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.2641 - acc: 0.9120Epoch 00003: val_loss improved from 0.72556 to 0.67831, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 2s 275us/step - loss: 0.2662 - acc: 0.9109 - val_loss: 0.6783 - val_acc: 0.8000
Epoch 4/20
6560/6680 [============================>.] - ETA: 0s - loss: 0.1816 - acc: 0.9424Epoch 00004: val_loss did not improve
6680/6680 [==============================] - 2s 275us/step - loss: 0.1806 - acc: 0.9424 - val_loss: 0.6910 - val_acc: 0.8024
Epoch 5/20
6520/6680 [============================>.] - ETA: 0s - loss: 0.1225 - acc: 0.9615Epoch 00005: val_loss did not improve
6680/6680 [==============================] - 2s 285us/step - loss: 0.1217 - acc: 0.9620 - val_loss: 0.7163 - val_acc: 0.8036
Epoch 6/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.0869 - acc: 0.9745Epoch 00006: val_loss improved from 0.67831 to 0.66808, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 2s 275us/step - loss: 0.0875 - acc: 0.9741 - val_loss: 0.6681 - val_acc: 0.8192
Epoch 7/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.0633 - acc: 0.9803Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 2s 274us/step - loss: 0.0638 - acc: 0.9802 - val_loss: 0.7218 - val_acc: 0.8096
Epoch 8/20
6480/6680 [============================>.] - ETA: 0s - loss: 0.0492 - acc: 0.9858Epoch 00008: val_loss improved from 0.66808 to 0.66136, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 2s 279us/step - loss: 0.0492 - acc: 0.9859 - val_loss: 0.6614 - val_acc: 0.8263
Epoch 9/20
6520/6680 [============================>.] - ETA: 0s - loss: 0.0358 - acc: 0.9903Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 2s 276us/step - loss: 0.0355 - acc: 0.9904 - val_loss: 0.7275 - val_acc: 0.8132
Epoch 10/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.0289 - acc: 0.9928Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 2s 277us/step - loss: 0.0289 - acc: 0.9928 - val_loss: 0.7516 - val_acc: 0.8084
Epoch 11/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.0232 - acc: 0.9943Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 2s 281us/step - loss: 0.0231 - acc: 0.9943 - val_loss: 0.7832 - val_acc: 0.8323
Epoch 12/20
6480/6680 [============================>.] - ETA: 0s - loss: 0.0167 - acc: 0.9961Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 2s 275us/step - loss: 0.0174 - acc: 0.9958 - val_loss: 0.8038 - val_acc: 0.8156
Epoch 13/20
6520/6680 [============================>.] - ETA: 0s - loss: 0.0156 - acc: 0.9966Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 2s 275us/step - loss: 0.0153 - acc: 0.9967 - val_loss: 0.8062 - val_acc: 0.8120
Epoch 14/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.0130 - acc: 0.9967Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 2s 274us/step - loss: 0.0130 - acc: 0.9967 - val_loss: 0.8173 - val_acc: 0.8251
Epoch 15/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.0094 - acc: 0.9970Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 2s 269us/step - loss: 0.0093 - acc: 0.9970 - val_loss: 0.8627 - val_acc: 0.8144
Epoch 16/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.0096 - acc: 0.9974Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 2s 275us/step - loss: 0.0095 - acc: 0.9975 - val_loss: 0.8554 - val_acc: 0.8240
Epoch 17/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.0077 - acc: 0.9982Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 2s 273us/step - loss: 0.0077 - acc: 0.9982 - val_loss: 0.8999 - val_acc: 0.8192
Epoch 18/20
6500/6680 [============================>.] - ETA: 0s - loss: 0.0087 - acc: 0.9983Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 2s 273us/step - loss: 0.0085 - acc: 0.9984 - val_loss: 0.8898 - val_acc: 0.8240
Epoch 19/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.0069 - acc: 0.9979Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 2s 294us/step - loss: 0.0069 - acc: 0.9979 - val_loss: 0.9223 - val_acc: 0.8299
Epoch 20/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.0051 - acc: 0.9985Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 2s 276us/step - loss: 0.0051 - acc: 0.9985 - val_loss: 0.9748 - val_acc: 0.8144
In [100]:
training2 = pd.DataFrame.from_dict(hist2.history)
training2.plot(secondary_y=['acc', 'val_acc'])
Out[100]:
<matplotlib.axes._subplots.AxesSubplot at 0x7fad54dc8dd8>

(IMPLEMENTATION) Load the Model with the Best Validation Loss

In [101]:
### TODO: Load the model weights with the best validation loss.

Resnet50_model.load_weights('saved_models/weights.best.Resnet50.hdf5')

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

In [102]:
### TODO: Calculate classification accuracy on the test dataset.

# get index of predicted dog breed for each image in test set
Resnet50_predictions = [np.argmax(Resnet50_model.predict(np.expand_dims(feature, axis=0))) for feature in test_Resnet50]

# report test accuracy
test_accuracy_Resnet50 = 100*np.sum(np.array(Resnet50_predictions)==np.argmax(test_targets, axis=1))/len(Resnet50_predictions)
print('Test accuracy: %.4f%%' % test_accuracy_Resnet50)
Test accuracy: 80.6220%

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

Similar to the analogous function in Step 5, your function should have three steps:

  1. Extract the bottleneck features corresponding to the chosen CNN model.
  2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
  3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function

extract_{network}

where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.

In [103]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.

def Resnet50_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_Resnet50(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = Resnet50_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]
In [104]:
#quick test on the dog_files_short set

print (dog_files_short[0])
display(Image(dog_files_short[0], width=200, height=200))
Resnet50_predict_breed(dog_files_short[0])
/data/dog_images/train/095.Kuvasz/Kuvasz_06442.jpg
Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5
94658560/94653016 [==============================] - 2s 0us/step
Out[104]:
'in/095.Kuvasz'

Step 6: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [105]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.

def who_let_the_dogs_out(img_path):
    if face_detector(img_path):
        print ('Hello human.')
        display(Image(img_path, width=200, height=200))
        breed = Resnet50_predict_breed(img_path)
        print ('You look like a...\n',breed)
    elif dog_detector(img_path):
        print ('Hello fury friend.')
        breed = Resnet50_predict_breed(img_path)
        display(Image(img_path, width=200, height=200))
        print ('You look like a...\n',breed)
    else:
        print ("Somethings gone wrong here. I don't see either a dog or a human here. Please try a different image.")
        display(Image(img_path, width=200, height=200))
    return None
In [109]:
##quick test

image_index = 13
In [110]:
display(Image(dog_files_short[image_index], width=200, height=200))
In [111]:
who_let_the_dogs_out(dog_files_short[image_index])
Hello fury friend.
You look like a...
 in/053.Cocker_spaniel

Step 7: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer:

In [112]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.

test_imgs = []

for file in glob("test_imgs/*.jpg"):
    test_imgs.append(file)
In [113]:
test_imgs
Out[113]:
['test_imgs/IMG_20161224_214357.jpg',
 'test_imgs/IMG_20190202_132446.jpg',
 'test_imgs/IMG_20180120_100219.jpg']

Accuracy on dogs

To start with, these were three recent photos of dogs I had on my phone.

  1. The first image is a winner. That is a dog and it's an Irish Setter mix named Lore. So Yay!
  2. The second one is again Lore but for some reason I believe the Face Detector is seeing Frida Karlos face on the pillow in the foreground. I'll check this in a code cell below.
  3. The thrid one is more surprising. It's a picture of a dog. Hmmm. I'll check the Face Detector for this one too below.
In [114]:
find_face(test_imgs[1])
Number of faces detected: 2
[[1837  499   51   51]
 [ 269 1046   54   54]] 

In [115]:
find_face(test_imgs[2])
Number of faces detected: 1
[[1344 3389   51   51]] 

  • The face fetector see's two tiny faces in the second image (test_imgs[1]). The rectangles are drawn but they are hard to see as they are small. They are on the christmas decoration hanging from the window handle and on the books sitting on the window sill.
  • When I run the code block above for the third image (test_imgs[2]), I get a similar result. The face detector is seeing a face in image on the edge of seat in what looks to be a strange, very darka area of the image.
  • I wonder if this is due to the input images being much larger in size therefore there is a much larger oppurtunity for the face detector to find a face. I will rescale the images to 224 by 224 as with the other images and see if this improves the result.
In [116]:
## as above, after investigating what the CV face detector was seeing, I rescaled the dog images to 224 by 224 pixels.
## stolen from here: https://www.daniweb.com/programming/software-development/code/216637/resize-an-image-python

from PIL import Image as IMG

height = 224
width = 224

index = 0
index1 = 1

while index < len(test_imgs):
    file = IMG.open(test_imgs[index])
    newfile = file.resize((width, height), IMG.NEAREST)
    ext = ".jpg"
    newfile.save('test_imgs/' + "NEAREST" + str(index1) + ext)
    index += 1
    index1 += 1
In [117]:
test_imgs_rescale = []

for file in glob("test_imgs/NEAREST*"):
    test_imgs_rescale.append(file)
In [118]:
test_imgs_rescale
Out[118]:
['test_imgs/NEAREST1.jpg', 'test_imgs/NEAREST2.jpg', 'test_imgs/NEAREST3.jpg']
In [119]:
for img in test_imgs_rescale:
    who_let_the_dogs_out(img)
    print("\n")
Hello fury friend.
You look like a...
 in/047.Chesapeake_bay_retriever


Somethings gone wrong here. I don't see either a dog or a human here. Please try a different image.

Somethings gone wrong here. I don't see either a dog or a human here. Please try a different image.

  • After rescaling, the second and third images now show neither a human or a dog. I'm still surprised about the thrid image as that is fairly clearly a dog in my opinion.
  • Let's now set it loose on headshots from the Golden State Warriors current roster and see what we get. All the images are .png so we can easily create a separate list and pass them to the function.
In [120]:
warriors_imgs = []

for file in glob("test_imgs/*.png"):
    warriors_imgs.append(file)
In [121]:
for img in warriors_imgs:
    who_let_the_dogs_out(img)
    print("\n")
Hello human.
You look like a...
 in/016.Beagle


Hello human.
You look like a...
 in/016.Beagle


Hello human.
You look like a...
 in/016.Beagle


Hello human.
You look like a...
 in/016.Beagle


Hello human.
You look like a...
 in/016.Beagle


Hello human.
You look like a...
 in/016.Beagle


Hello human.
You look like a...
 in/041.Bullmastiff


Hello human.
You look like a...
 in/016.Beagle


Hello human.
You look like a...
 in/041.Bullmastiff


Hello human.
You look like a...
 in/016.Beagle


Hello human.
You look like a...
 in/016.Beagle


Hello human.
You look like a...
 in/016.Beagle


Hello human.
You look like a...
 in/041.Bullmastiff


Hello human.
You look like a...
 in/041.Bullmastiff


Hello human.
You look like a...
 in/016.Beagle


Hello human.
You look like a...
 in/016.Beagle


  • Yay! It recogniszed all the humans as humans and we have range of different breeds it predicts.

Overall Performance:

  • I'm fairly surprised how well it performs. I'd concede that the second dog photo is a tough one so I'm not surprised it doesn't see either a human or dog. I'm still surprised by the thrid dog photo though, I feel like it should recognise a dog there. It's performance on the human photos is satisfying.

Improvements:

  1. Whilst I'm satisfied with the ~80% accuracy, I believe there is optimization to do on the Model Architecture to get this closer to 95%.
  2. Including Data Augmentation on the training set could help to improve the performance.
  3. I could use a different face detector and/or dog detector algorithm which are both crucial elements of this function.

Please download your notebook to submit

In order to submit, please do the following:

  1. Download an HTML version of the notebook to your computer using 'File: Download as...'
  2. Click on the orange Jupyter circle on the top left of the workspace.
  3. Navigate into the dog-project folder to ensure that you are using the provided dog_images, lfw, and bottleneck_features folders; this means that those folders will not appear in the dog-project folder. If they do appear because you downloaded them, delete them.
  4. While in the dog-project folder, upload the HTML version of this notebook you just downloaded. The upload button is on the top right.
  5. Navigate back to the home folder by clicking on the two dots next to the folder icon, and then open up a terminal under the 'new' tab on the top right
  6. Zip the dog-project folder with the following command in the terminal: zip -r dog-project.zip dog-project
  7. Download the zip file by clicking on the square next to it and selecting 'download'. This will be the zip file you turn in on the next node after this workspace!